package com.jay.codec.soft

import android.util.Log
import com.jay.codec.soft.mp3.DataFrameSpec
import com.jay.codec.soft.mp3.FrameHeader
import java.io.File
import java.io.FileInputStream
import kotlin.experimental.and

/**
 * @author xuzhou4
 * @date 2021/12/31
 */
object CodecUtils {

    private const val TAG = "codec_utils"

    fun parseMP3(path: String) {
        Log.d(TAG, "parseMP3() called with: path = $path")

        val file = File(path)
        val fileInputStream = FileInputStream(file)

        var byteArray = ByteArray(10)

//        var len = fileInputStream.read(byteArray, 0, 10)
        val header = String(byteArray, 0, 3);
        Log.d(TAG, "mp3 Header : $header")

        if ("ID3" == header) {

            //解析文件ID3V2信息
            Log.d(TAG, "mp3 Ver : ID3V2.${byteArray[3]}")
            Log.d(TAG, "mp3 Revision : ${byteArray[4]}")

            Log.d(TAG, "mp3 Flag : ${byteArray[5]}")

            var size = (byteArray[6] and 0x7F) * 0x200000 + (byteArray[7] and 0x7F) * 0x400 + (byteArray[8] and 0x7F) * 0x80 + (byteArray[9] and 0x7F)
            Log.d(TAG, "mp3 Size : $size")

            var leftSize = size
            var pos = 0
            byteArray = ByteArray(leftSize)
//            len = fileInputStream.read(byteArray, 0, leftSize)

            var labelID = String(byteArray, pos, 4)
            while (DataFrameSpec.WXXX.isDataFrameSpec(labelID)) {
                Log.d(TAG, "mp3 label Id    : $labelID")
                var dataSize =
                    byteArray[pos + 4] * 0x1000000 + byteArray[pos + 5] * 0x10000 + byteArray[pos + 6] * 0x100 + byteArray[pos + 7]
                Log.d(TAG, "mp3 label size  : $dataSize")

                Log.d(TAG, "mp3 label flag  : ${byteArray[pos + 8] * 0x100 + byteArray[pos + 9]}")

                val bytes = ByteArray(dataSize)
                System.arraycopy(byteArray, pos + 9, bytes, 0, dataSize)
                Log.d(TAG, "mp3 label data  : ${String(bytes)}")

                pos += 10 + dataSize
                if (pos < leftSize) {
                    labelID = String(byteArray, pos, 4)
                } else {
                    break
                }
            }

            //读取数据
            val frameHeaderBytes = ByteArray(4)
            fileInputStream.read(frameHeaderBytes,0, 4)

//            val frameHeader = FrameHeader(frameHeaderBytes)
        }

        fileInputStream.close()
    }
}